package com.firexxx.study.performancetest.task;

import lombok.Getter;
import lombok.Setter;

/**
 * 任务基础类
 *
 * @author fireXXX
 * @date 2020/11/19 0:14
 **/
public abstract class ITask implements Runnable {

    @Setter
    @Getter
    private boolean runStatus = true;

    @Getter
    @Setter
    private long pv = 0;

    @Getter
    private long pvMax = 0;

    @Override
    public void run() {
        while (isRunning() && pvValid()) {
            try {
                saveResult(runOne());
                pv++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        runStatus = false;
    }

    private boolean pvValid() {
        if (pvMax == 0) {
            return true;
        }

        return pv < pvMax;
    }

    public abstract Object runOne();

    abstract void saveResult(Object obj);

    abstract void init(Object args);

    public void setPvMax(long max) {
        pvMax = max;
    }

    public void stop() {
        runStatus = false;

        persist();
    }

    public void persist() {
        //TODO 数据持久化
    }

    public boolean isRunning() {
        return runStatus;
    }

}